<template>
  <div class="person_container">
    <!-- 头部导航 -->
    <div class="header">
      <el-menu background-color="#eee" text-color="#303133" class="el-menu-demo" mode="horizontal" router>
        <el-menu-item index="/home">首页</el-menu-item>
        <el-menu-item>个人商圈管理</el-menu-item>
      </el-menu>
    </div>

    <!-- 消费分析 -->
    <transition class="consumption_analyze" name="component-fade">
      <CCA v-if="isConsumptionAnalyzeShow" :isConsumptionAnalyzeShow="isConsumptionAnalyzeShow" @fade="isConsumptionAnalyzeShow = false" :personRow="personRow"/>

      <!-- 主页面 -->
      <div class="personMain" v-else>
        <!-- 表单区域 -->
        <el-form ref="personFormRef" :model="personForm" inline>
          <el-form-item label="用户ID/昵称" prop="user">
            <el-input v-model="personForm.user" class="store_num"></el-input>
          </el-form-item>
          <el-form-item label="日期" prop="time1">
            <el-date-picker v-model="personForm.time1" type="date" placeholder="选择日期"> </el-date-picker>
          </el-form-item>
          <el-form-item label="至" prop="time2">
            <el-date-picker v-model="personForm.time2" type="date" placeholder="选择日期"> </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button class="submit" @click="onSubmit">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 统计区域 -->
        <el-row :gutter="18" class="statistics">
          <el-col :span="6"
            ><div class="grid-content bg-purple">用户数量：{{ user_num }}</div></el-col
          >
          <el-col :span="6"
            ><div class="grid-content bg-purple">订单量：{{ order_num }}</div></el-col
          >
          <el-col :span="6"
            ><div class="grid-content bg-purple">{{ `消费总额：${expenditure}元` }}</div></el-col
          >
        </el-row>

        <!-- 表格渲染区域 -->
        <el-card class="main">
          <el-table :data="personData" style="width: 100%">
            <el-table-column prop="u_id" label="用户ID"></el-table-column>
            <el-table-column prop="u_name" label="用户昵称"> </el-table-column>
            <el-table-column prop="phone" label="联系电话"> </el-table-column>
            <el-table-column prop="store_num" label="商圈店铺数量"> </el-table-column>
            <el-table-column prop="order_num" label="订单量"> </el-table-column>
            <el-table-column label="消费额">
              <template slot-scope="scope">
                {{ `${scope.row.money}元` }}
              </template>
            </el-table-column>
            <el-table-column label="消费频次">
              <template slot-scope="scope">
                {{ `${scope.row.consumption_num}次/天` }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-link type="primary" @click="handle(scope.row)"> 消费分析 </el-link>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </transition>
  </div>
</template>

<script>
import dayjs from 'dayjs'

import CCA from '../components/CCA'

export default {
  name: 'PersonIndex',
  created() {
    this.loadPersonData()
  },
  components: {
    CCA
  },
  data() {
    return {
      personForm: {
        user: '',
        time1: '',
        time2: ''
      },
      personData: [],
      // 用户数量
      user_num: '',
      // 订单量
      order_num: 0,
      // 消费总额
      expenditure: 0,
      // 控制消费分析模块显示与隐藏
      isConsumptionAnalyzeShow: false,
      // 当前点击用户的数据对象
      personRow: {}
    }
  },
  methods: {
    // 加载个人商圈数据
    async loadPersonData() {
      // 问题 : 每次发请求 , 统计的数据都会翻倍增长
      // 原因 : watch监听了personData数据的变化,只要personData发生变化就会发生计算赋值
      // 解决 : 发请求前手动清空统计模块数据,且实验了一下好像只能在这清空
      // this.order_num = 0
      // this.user_num = ''
      // this.expenditure = 0

      const { data } = await this.$http.get('/person')
      this.personData = data
    },
    // 点击重置表单
    resetForm() {
      this.$refs.personFormRef.resetFields()
      // 重置表单时发送请求获取全部数据
      this.loadPersonData()
    },
    // 点击查询提交表单
    async onSubmit() {
      // 表单的两个都为空时获取所有数据
      if (this.personForm.user + this.personForm.time1 + this.personForm.time2 === '') {
        this.loadPersonData()
      }

      // 清空personData是为了查询到数据后, 让表格渲染查询到的数据
      this.personData = []

      // 如果第一个表单项不为空
      if (this.personForm.user !== '') {
        // 发请求查询用户ID的匹配项
        const { data: res1 } = await this.$http.get(`/person?u_id_like=${this.personForm.user}`)
        this.personData = res1

        // 发请求查询用户昵称的匹配项
        const { data: res2 } = await this.$http.get(`/person?u_name_like=${this.personForm.user}`)
        // 为了防止两次数据有重复的数据
        // 先遍历res2
        res2.forEach((item) => {
          // 如果personData的数据没有id和res2数据重合的
          if (!this.personData.find((subitem) => subitem.u_id === item.u_id)) {
            // 就添加到personData中
            this.personData.push(item)
          }
        })
      }

      // 查询时间时, 其中一个时间框必须有值才可以进入条件查询
      if (this.personForm.time1 || this.personForm.time2) {
        var startDate = ''
        var endDate = ''
        // 如果第二个事件表单项 time1 不为空
        if (this.personForm.time1) {
          // 转换字符串格式代码 为请求做准备
          startDate = dayjs(this.personForm.time1).format('YYYY-MM-DD')
        }
        // 如果第二个事件表单项 time2 不为空
        if (this.personForm.time2) {
          // 转换字符串格式代码 为请求做准备
          endDate = dayjs(this.personForm.time2).format('YYYY-MM-DD')
        }
        console.log(startDate, endDate)

        // 拼接GET请求查询参数
        var filter = startDate ? 'time_gte=' + startDate : ''
        // 如果 开始时间为空
        if (filter === '') {
          filter += endDate ? 'time_lte=' + endDate : ''
        } else {
          // 开始时间不为空,
          filter += endDate ? '&time_lte=' + endDate : ''
        }

        const { data: res } = await this.$http.get(`/person?${filter}`)
        res.forEach((item) => {
          if (!this.personData.find((subitem) => subitem.u_id === item.u_id)) {
            this.personData.push(item)
          }
        })
      }

      var str = this.personForm.time2 + this.personForm.time1 + this.personForm.user
      if (str === '' || str === 'null') {
        this.loadPersonData()
      }
    },
    handle(row) {
      this.isConsumptionAnalyzeShow = !this.isConsumptionAnalyzeShow
      this.personRow = row
    }
  },
  watch: {
    personData(data) {
      // 问题: 重置表单时统计数据 翻倍增长问题解决, 但查询时数据还是会不正确
      // 原因: 还是watch监听personData数据时,只要有变化就会重新赋值计算 但是原有数据没有清空
      // 解决: 在监听数据发生变化时, 在赋值计算之前先将数据手动清空
      this.order_num = 0
      this.user_num = ''
      this.expenditure = 0

      this.user_num = data.length

      data.forEach((item) => {
        this.order_num += item.order_num
        this.expenditure += item.money
      })
    }
  }
}
</script>

<style lang="less" scoped>
.person_container {
  width: 100%;
  .header {
    .el-button {
      margin-left: 0;
    }
  }

  .el-form {
    margin: 10px 10px 0;
    // height: 73px;
    padding-left: 15px;
    border: 1px solid #797979;
    border-radius: 6px;
    line-height: 73px;
    .el-form-item {
      height: 100%;
      margin-bottom: 0;
      .store_num {
        width: 200px;
        margin-right: 30px;
      }
      /deep/ .el-form-item__label {
        line-height: unset;
      }
      /deep/ .el-form-item__content {
        line-height: unset;
      }

      span {
        margin: 0 10px 0 48px;
        color: #606266;
      }
      .submit {
        margin: 0 28px 0 80px;
      }
    }
  }

  .statistics {
    padding: 10px 20px;
    color: #606266;
    font-size: 14px;
  }

  .main {
    // height: 600px;
    margin: 0 10px 0;
    border: 1px solid #797979;
    border-radius: 6px;
    /deep/ .el-card__body {
      padding: 10px 10px 0;
    }
    /deep/ .el-table__header-wrapper {
      box-sizing: border-box;
      border: 1px solid #797979;
      border-radius: 6px;
    }
  }

  // .fade-enter,
  // .fade-leave-to {
  //   opacity: 0;
  //   transform: translateX(-100px);
  // }

  // .fade-enter-active,
  // .fade-leave-active {
  //   transition: all 1s ease;
  //   position: absolute;
  // }
  .component-fade-enter-active,
  .component-fade-leave-active {
    transition: translateX(-100px) 0.1s ease;
  }
  .component-fade-enter, .component-fade-leave-to
/* .component-fade-leave-active for below version 2.1.8 */ {
    transition: all 1s ease;
    position: absolute;
    opacity: 0;
  }
}
</style>
